package csu.webcourse.mypetstore.web.servlet;

import csu.webcourse.mypetstore.domain.Account;
import csu.webcourse.mypetstore.domain.Product;
import csu.webcourse.mypetstore.service.AccountService;
import csu.webcourse.mypetstore.service.CategoryService;
import csu.webcourse.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RegisterServlet extends HttpServlet {
    private static final String NEW_ACCOUNT = "/WEB-INF/jsp/account/newAccountForm.jsp";

    private static final List<String> LANGUAGE_LIST;

    private static final List<String> CATEGORY_LIST;

    static {
        List<String> langList = new ArrayList<String>();
        langList.add("english");
        langList.add("japanese");
        LANGUAGE_LIST = Collections.unmodifiableList(langList);

        List<String> catList = new ArrayList<String>();
        catList.add("FISH");
        catList.add("DOGS");
        catList.add("REPTILES");
        catList.add("CATS");
        catList.add("BIRDS");
        CATEGORY_LIST = Collections.unmodifiableList(catList);
    }

    private Account account;
    private AccountService accountService;
    private CategoryService categoryService;
    private String msg;
    private List<Product> myList;
    private boolean authenticated;
    private String checkCode;
    private String checkCode1;
    private PrintWriter respOut;

    public Account getAccount() {
        return this.account;
    }

    public List<Product> getMyList() {
        return myList;
    }

    public void setMyList(List<Product> myList) {
        this.myList = myList;
    }

    public List<String> getLanguages() {
        return LANGUAGE_LIST;
    }

    public List<String> getCategories() {
        return CATEGORY_LIST;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain");
        respOut = resp.getWriter();
        account = new Account();
        accountService = new AccountService();
        categoryService = new CategoryService();
        this.account.setUsername(req.getParameter("username"));
        this.account.setPassword(req.getParameter("password"));
        this.account.setFirstName(req.getParameter("account.firstName"));
        this.account.setLastName(req.getParameter("account.lastName"));
        this.account.setEmail(req.getParameter("account.email"));
        this.account.setPhone(req.getParameter("account.phone"));
        this.account.setAddress1(req.getParameter("account.address1"));
        this.account.setAddress2(req.getParameter("account.address2"));
        this.account.setCity(req.getParameter("account.city"));
        this.account.setState(req.getParameter("account.state"));
        this.account.setZip(req.getParameter("account.zip"));
        this.account.setCountry(req.getParameter("account.country"));
        this.account.setLanguagePreference(req.getParameter("account.languagePreference"));
        this.account.setFavouriteCategoryId(req.getParameter("account.favouriteCategoryId"));
        this.account.setListOption(true);
        this.account.setBannerOption(true);
        checkCode1 = req.getParameter("checkCode");
        HttpSession session1 = req.getSession();
        checkCode = (String) session1.getAttribute("checkCode");
        if (checkUserName())
        if (!validate()){
            req.setAttribute("registerMsg", this.msg);
        }else {
            accountService.insertAccount(account);
            account = accountService.getAccount(account.getUsername(),account.getPassword());
            myList = categoryService.getProductListByCategory(account.getFavouriteCategoryId());
            authenticated = true;

            HttpSession session = req.getSession();
            Account account = (Account) session.getAttribute("loginAccount");
            if (account != null) {
                HttpServletRequest httpRequest = req;
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

                LogService logService = new LogService();
                //最后加入的信息“XXXXX”应当为该界面的信息以及一些商品信息
                String logInfo = logService.logInfo(" ") + strBackUrl + "用户注册成功，返回主界面";
                logService.insertLogInfo(account.getUsername(), logInfo);
            }

            resp.sendRedirect("mainForm");
        }

    }

    private boolean validate() {
        if(this.account.getUsername() == null || this.account.getUsername().equals("")) {
            return false;
        }
        if(this.account.getPassword() == null || this.account.getPassword().equals("")) {
            return false;
        }
        if( this.account.getFirstName() == null || this.account.getFirstName().equals("")) {
            return false;
        }
        if(this.account.getLastName() == null || this.account.getLastName().equals("")) {
            return false;
        }
        if(this.account.getEmail() == null || this.account.getEmail().equals("")) {
            return false;
        }
        if(this.account.getPhone() == null || this.account.getPhone().equals("")) {
            return false;
        }
        if(this.account.getAddress1() == null || this.account.getAddress1().equals("")) {
            return false;
        }
        if(this.account.getAddress2() == null || this.account.getAddress2().equals("")) {
            return false;
        }
        if(this.account.getCity() == null || this.account.getCity().equals("")) {
            return false;
        }
        if(this.account.getState() == null || this.account.getState().equals("")) {
            return false;
        }
        if(this.account.getZip() == null || this.account.getZip().equals("")) {
//            this.respOut.print("邮编不能为空");
            return false;
        }if(this.account.getCountry() == null || this.account.getCountry().equals("")) {
//            this.respOut.print("国家不能为空");
            return false;
        }
        if (!this.checkCode.equalsIgnoreCase(checkCode1)){
//            this.respOut.print("验证码错误");
            return false;
        }
        return true;
    }

    private boolean checkUserName(){
        if (accountService.getAccount(this.account.getUsername()) == null){
            respOut.print("username valid");
            return true;
        }
        respOut.print("username exist");
        return false;
    };
}
